public without sharing class InstrumentPolicyHandler {
    
    public static void setActive(List<InstrumentPolicy__c> list_new  , Map<Id,InstrumentPolicy__c> oldMap ){


    	Map<Id,Id> insMap = new Map<Id,Id>();

        List<Opportunity> oppList = new List<Opportunity>();
    	for(InstrumentPolicy__c ip : list_new){

    		InstrumentPolicy__c oldIp  =oldMap.get(ip.Id);

            if(ip.Status__c == '审批中(销售主管已批准)' && oldIp.Status__c != '审批中(销售主管已批准)' && ip.Confirm__c != true ){

                ip.addError('请点击“编辑/查看仪器销售政策”按钮后点击”确认并保存“，成功后才能审批(政策内容如需修改，请修改后点击确认并保存，否则无法审批)');
                return;
            }
    		if(ip.Status__c == '已批准' && oldIp.Status__c !='已批准'  ){

    		   ip.Active__c = true;
    		   insMap.put(ip.Id , ip.Opportunity__c);


                Opportunity opp = new Opportunity();
                opp.Id = ip.Opportunity__c;
                opp.InstrumentPolicy__c = ip.Id ; 
                oppList.add(opp);

    		}

    	}
        if(oppList.size() > 0) update oppList;


    	List<InstrumentPolicy__c> tmp = new List<InstrumentPolicy__c>();
    	for(InstrumentPolicy__c ip : [select Id ,Active__c from   InstrumentPolicy__c where Opportunity__c in:insMap.values()   and Id not in:insMap.keySet()   ]){
    		ip.Active__c = false;
    		tmp.add(ip);
    	}

    	if(tmp.size() > 0 )update tmp;
    }

    //计算明细中是否有自产产品
    public static void calcZc(Map<Id,InstrumentPolicy__c> qM ){
        
        System.debug(qM);   
       Map<Id,String> tMap = new Map<Id,String>();
        Map<Id,Set<Id>> mMap = new Map<Id,Set<Id>>();

        for (InstrumentPolicy__c q : qM.values() ) {
           
           Set<Id> m = mMap.containsKey(q.Opportunity__c ) ? mMap.get(q.Opportunity__c) : new Set<Id>();
           m.add(q.Id );
           mMap.put(q.Opportunity__c, m );

        }


        Set<String> companys = new Set<String>();
        Set<String> provinces = new Set<String>();
        Map<String,String> mProvinces= new Map<String,String>();
        for (Opportunity opp : [select Id ,AccountId,Account.InstCompany__c  from Opportunity where Id in: mMap.keySet() ] ) {
           String company = opp.Account.InstCompany__c == null ? 'MKSW' : opp.Account.InstCompany__c; 
          String province = CompanyProvinceUtil.getCompanyCodeAndProvince(company).get(0) ;
          company = CompanyProvinceUtil.transCodeToName(company);
            companys.add(company );
            provinces.add( province);

            mProvinces.put(opp.Id , company+province);
            
        }
        System.debug(companys);

        Set<Id> pids = new Set<Id>();
        List<InstrumentMarketingPolicy__c> qpList  =[select InstrumentPolicy__r.Opportunity__c , InstrumentPolicy__c,Quantity__c,Product__c,Product__r.Brand__c,Product__r.NCCode__c,Product__r.Category1__c,Product__r.Category0__c  from InstrumentMarketingPolicy__c where InstrumentPolicy__c in:qM.keySet()  ];
       
       for(InstrumentMarketingPolicy__c qp :  qpList ){

            String type  = tMap.get(qp.InstrumentPolicy__c);
             if( MaccuraBrandUtil.maccura.contains(qp.Product__r.Brand__c) || MaccuraBrandUtil.maccura.contains(qp.Product__r.NCCode__c) || (qp.Product__r.Category1__c == '生化' &&  qp.Product__r.Category0__c == '仪器' )) {
                if( qp.Product__r.Category0__c == '仪器' )pids.add(qp.Product__c);
               
                type = (type == null ||  !type.contains('非自产') ) ? '自产' :'自产/非自产';
                  
             }else{

                 type = ( type == null || type == '非自产'   ) ? '非自产' :'自产/非自产';

             }
            tMap.put(qp.InstrumentPolicy__c, type);
       }

      Map<String ,Decimal> priceMap = new Map<String,Decimal>();
       for (Price__c p :[select Id,Product__c,Company__c ,Province__c ,InstCost__c from Price__c where Product__c in: pids and Company__c in : companys and Province__c in: provinces and ClosePrice__c != true ] ) {
          priceMap.put(p.Product__c+p.Company__c+p.Province__c, p.InstCost__c);
       }

       
       Map<String,Decimal> mT = new Map<String ,Decimal>();
       for(InstrumentMarketingPolicy__c qp :  qpList ){

          if( MaccuraBrandUtil.maccura.contains(qp.Product__r.Brand__c) || MaccuraBrandUtil.maccura.contains(qp.Product__r.NCCode__c) || (qp.Product__r.Category1__c == '生化' &&  qp.Product__r.Category0__c == '仪器' )) {
               Decimal t =  mT.containsKey(qp.InstrumentPolicy__c)  ? mT.get(qp.InstrumentPolicy__c) : 0;
               String key = qp.Product__c+ mProvinces.get(qp.InstrumentPolicy__r.Opportunity__c );
               
               t+= (priceMap.get(key) == null ? 0 :priceMap.get(key)) * (qp.Quantity__c == null ? 0 : qp.Quantity__c );
              mT.put(qp.InstrumentPolicy__c,t);
          }
       }


       for ( InstrumentPolicy__c q : qM.values() ) {
           
           q.ZC__c = tMap.get(q.Id);
           q.SelfProductionCostCount__c = mt.get(q.Id );


       }





    }

    public static void countField(List<InstrumentMarketingPolicy__c> list_new){

        Map<Id,InstrumentPolicy__c> inpMap =new Map<Id,InstrumentPolicy__c>();
        for(InstrumentMarketingPolicy__c imp : list_new){

            inpMap.put(imp.InstrumentPolicy__c,new InstrumentPolicy__c(
                
                Id=imp.InstrumentPolicy__c ,
                IsSame__c = true ,
                TYEquipment__c= null,
                MYEquipment__c = null, 
                SHEquipment__c = null, 
                BLEquipment__c = null, 
                XXEquipment__c = null, 
                XYEquipment__c = null, 
                MKYEquipment__c = null, 
                THEquipment__c = null, 

                NoSpecificItems__c = null, 
                LessThanTaskQuantityNumber__c = null, 
                LowerThanEarnestMoney__c = null, 
                LowerThanMaintenanceCost__c = null, 

                LowerThanSalesPrice__c = null, 
                LowerThanRentalFee__c = null

              ) 
            );
           
            
        }
        

        for(InstrumentMarketingPolicy__c imp : [select Id ,AmountPurchased__c,EarnestMoney__c,RentalFee__c,
            MaintenanceCost__c,SalePrice__c,BloodCardNumber__c,
            InstrumentPolicy__c  ,MarketingPolicy__r.Product__r.Category1__c ,MarketingPolicy__r.BloodCardPurchased__c,
            MarketingPolicy__r.AmountPurchased__c ,MarketingPolicy__r.EarnestMoney__c ,MarketingPolicy__r.RentalFee__c , 
            MarketingPolicy__r.SalePrice__c ,SpecificItems__c,MarketingPolicy__r.MaintenanceCost__c ,
            CooperationPeriod__c,MarketingPolicy__r.CooperationPeriod__c,
            TaskIndicatorRebate1__c,MarketingPolicy__r.TaskIndicatorRebate1__c , 
            PresentingReagent__c,MarketingPolicy__r.PresentingReagent__c , 
            ReturnServiceFee__c ,MarketingPolicy__r.ReturnServiceFee__c , 
            ReturnServiceFeeRentalFee__c ,MarketingPolicy__r.ReturnServiceFeeRentalFee__c 

            from InstrumentMarketingPolicy__c where InstrumentPolicy__c in:inpMap.keySet() ]){
          InstrumentPolicy__c ip = inpMap.get(imp.InstrumentPolicy__c );


            if(imp.MarketingPolicy__r.Product__r.Category1__c == '体液') ip.TYEquipment__c =  ip.TYEquipment__c == null ? 1 :  ip.TYEquipment__c+1 ; 
            if(imp.MarketingPolicy__r.Product__r.Category1__c == '免疫') ip.MYEquipment__c =  ip.MYEquipment__c == null ? 1 :  ip.MYEquipment__c+1 ; 
            if(imp.MarketingPolicy__r.Product__r.Category1__c == '生化') ip.SHEquipment__c = ip.SHEquipment__c == null ? 1 :  ip.SHEquipment__c+1 ; 
            if(imp.MarketingPolicy__r.Product__r.Category1__c == '病理') ip.BLEquipment__c = ip.BLEquipment__c == null ? 1 :  ip.BLEquipment__c+1 ; 
            if(imp.MarketingPolicy__r.Product__r.Category1__c == '血型') ip.XXEquipment__c =  ip.XXEquipment__c == null ? 1 :  ip.XXEquipment__c+1 ; 
            if(imp.MarketingPolicy__r.Product__r.Category1__c == '血液') ip.XYEquipment__c = ip.XYEquipment__c == null ? 1 :  ip.XYEquipment__c+1 ; 
            if(imp.MarketingPolicy__r.Product__r.Category1__c == 'POCT') ip.MKYEquipment__c = ip.MKYEquipment__c == null ? 1 :  ip.MKYEquipment__c+1 ; 
            if(imp.MarketingPolicy__r.Product__r.Category1__c == '糖化') ip.THEquipment__c  = ip.THEquipment__c == null ? 1 :  ip.THEquipment__c+1 ; 

            if(imp.SpecificItems__c != null ) ip.NoSpecificItems__c = ip.NoSpecificItems__c == null ? 1 : ip.NoSpecificItems__c+1 ; 
            if( compareDecimal(imp.MarketingPolicy__r.AmountPurchased__c,imp.AmountPurchased__c )) ip.LessThanTaskQuantityNumber__c  = ip.LessThanTaskQuantityNumber__c == null ? 1 :  ip.LessThanTaskQuantityNumber__c+1 ;    
            if( compareDecimal(imp.MarketingPolicy__r.EarnestMoney__c,imp.EarnestMoney__c )) ip.LowerThanEarnestMoney__c = ip.LowerThanEarnestMoney__c == null ? 1 :  ip.LowerThanEarnestMoney__c+1 ;    
            if( compareDecimal(imp.MarketingPolicy__r.MaintenanceCost__c,imp.MaintenanceCost__c ))ip.LowerThanMaintenanceCost__c =  ip.LowerThanMaintenanceCost__c == null ? 1 :  ip.LowerThanMaintenanceCost__c+1 ;    
            if( compareDecimal(imp.MarketingPolicy__r.SalePrice__c,imp.SalePrice__c ))ip.LowerThanSalesPrice__c  = ip.LowerThanSalesPrice__c == null ? 1 :  ip.LowerThanSalesPrice__c+1 ;    
            if( compareDecimal(imp.MarketingPolicy__r.RentalFee__c,imp.RentalFee__c )) ip.LowerThanRentalFee__c = ip.LowerThanRentalFee__c == null ? 1 :  ip.LowerThanRentalFee__c+1 ;    



                 System.debug('CooperationPeriod__c  '+IsSame(imp.CooperationPeriod__c , imp.MarketingPolicy__r.CooperationPeriod__c )  ); 
                 System.debug('RentalFee__c  '+IsSame(imp.RentalFee__c , imp.MarketingPolicy__r.RentalFee__c  )  ); 
                 System.debug('AmountPurchased__c  '+IsSame(imp.AmountPurchased__c , imp.MarketingPolicy__r.AmountPurchased__c )  ); 
                 System.debug('TaskIndicatorRebate1__c  '+IsSame(imp.TaskIndicatorRebate1__c , imp.MarketingPolicy__r.TaskIndicatorRebate1__c )  ); 
                 System.debug('BloodCardNumber__c  '+IsSame(imp.BloodCardNumber__c , imp.MarketingPolicy__r.BloodCardPurchased__c )  ); 
                 System.debug('MaintenanceCost__c  '+IsSame(imp.MaintenanceCost__c , imp.MarketingPolicy__r.MaintenanceCost__c  ) );
                 System.debug('EarnestMoney__c  '+IsSame(imp.EarnestMoney__c , imp.MarketingPolicy__r.EarnestMoney__c  )   );   
                  System.debug('PresentingReagent__c  '+IsSame(imp.PresentingReagent__c , imp.MarketingPolicy__r.PresentingReagent__c  )  );
                 System.debug('ReturnServiceFee__c  '+IsSame(imp.ReturnServiceFee__c , imp.MarketingPolicy__r.ReturnServiceFee__c  )   );
                 System.debug('ReturnServiceFeeRentalFee__c  '+IsSame(imp.ReturnServiceFeeRentalFee__c , imp.MarketingPolicy__r.ReturnServiceFeeRentalFee__c ));
             

                System.debug('SalePrice__c  '+IsSame(imp.SalePrice__c , imp.MarketingPolicy__r.SalePrice__c ));
                

            if( !(IsSame(imp.SalePrice__c , imp.MarketingPolicy__r.SalePrice__c ) && 
                IsSame(imp.CooperationPeriod__c , imp.MarketingPolicy__r.CooperationPeriod__c ) && 
                IsSame(imp.RentalFee__c , imp.MarketingPolicy__r.RentalFee__c  ) && 
                IsSame(imp.AmountPurchased__c , imp.MarketingPolicy__r.AmountPurchased__c ) && 
                IsSame(imp.TaskIndicatorRebate1__c , imp.MarketingPolicy__r.TaskIndicatorRebate1__c ) && 
                IsSame(imp.BloodCardNumber__c , imp.MarketingPolicy__r.BloodCardPurchased__c ) && 
                IsSame(imp.MaintenanceCost__c , imp.MarketingPolicy__r.MaintenanceCost__c  )  &&
                IsSame(imp.EarnestMoney__c , imp.MarketingPolicy__r.EarnestMoney__c  )  &&
                IsSame(imp.PresentingReagent__c , imp.MarketingPolicy__r.PresentingReagent__c  )  &&
                IsSame(imp.ReturnServiceFee__c , imp.MarketingPolicy__r.ReturnServiceFee__c  )  &&
                IsSame(imp.ReturnServiceFeeRentalFee__c , imp.MarketingPolicy__r.ReturnServiceFeeRentalFee__c ))
              ) ip.IsSame__c = false;
            
        }
        System.debug('InstrumentPolicyHandler==>'+inpMap.values());

        if(inpMap.keySet().size() > 0 ) update inpMap.values();



    }
     public static Boolean IsSame(Decimal d1,Decimal d2 ){

        if(d1 == null)d1 =  0 ;
         if(d2 == null)d2=  0 ;
        return d1 ==  d2 ;  
    }
    public static Boolean compareDecimal(Decimal d1,Decimal d2 ){

        if(d1 == null)d1 =  0 ;
         if(d2 == null)d2=  0 ;
        return d1 > d2 ;  
    }


    public static void setOppStageName(List<InstrumentPolicy__c> newList, Map<Id, InstrumentPolicy__c> oldMap) {
        for (InstrumentPolicy__c q : newList) {
            InstrumentPolicy__c old = oldMap.get(q.Id);
            if (old.Status__c != q.Status__c && q.Status__c == '审批中') {
                // FIXME 审批只会一条一条来，所以允许在for循环里面写soql
                Opportunity opp = [select Id, RecordType.Name,StageName, ExecuteCompany__r.RecordType.DeveloperName from Opportunity where Id = :q.Opportunity__c];
                // if (opp.ExecuteCompany__r.RecordType.DeveloperName == 'Maccura') {
                    System.debug(q);
                    System.debug(opp);
                if(opp.StageName == '立项'){
                    opp.StageName = '方案谈判';
                // }
                    System.debug(opp);
                    update opp;
                }
            }
        }
    }
}